import usbManager from '@ohos.usbManager';
import router from '@system.router';
import CheckEmptyUtils from '../../utils/CheckEmptyUtils.js';
import DateUtils from '../../utils/DateAndTimeUtil.js';
import EventConstants from '../../utils/EventConstants.js'
import prompt from '@system.prompt';

export default {
    data: {
        result: 'World',
        device: null,
        config: null,
        pip: null,
        inEndpoint: null,
        outEndpoint: null,
        interface: null,
        usbInRequest: null,
        usbOutRequest: null,
        isInitOutRequest: false,
        isInitInRequest: false,
        inClientData: null,
        outClientData: null
    },
    onInit() {
        var deviceList = usbManager.getDevices();
        if (CheckEmptyUtils.isEmptyArr(deviceList)) {
            this.result = "init error ： 设备列表为空";
            console.info("usb request device is null");
            return;
        }
        this.device = deviceList[0];
        console.info("usb request device : " + JSON.stringify(this.device));

        if (CheckEmptyUtils.isEmptyArr(this.device.configs)) {
            this.result = "init error ： 设备configs列表为空";
            console.info("usb request configs is null");
            return;
        }
        this.config = this.device.configs[0]

        if (CheckEmptyUtils.isEmptyArr(this.config.interfaces)) {
            this.result = "init error ： 设备interfaces列表为空";
            console.info("usb request interfaces is null");
            return;
        }
        var interfaceSize = this.config.interfaces.length;
        console.info("usb request this.interface size: " + interfaceSize);

        for (let i = 0; i < interfaceSize; i++) {
            this.interface = this.config.interfaces[i];
            if (CheckEmptyUtils.isEmptyArr(this.interface.endpoints)) {
                continue;
            }
            for (let k = 0, len = this.interface.endpoints.length; k < len; k++) {
                let endpoint = this.interface.endpoints[k];
                if (endpoint.type == EventConstants.USB_ENDPOINT_XFER_BULK) {
                    if (endpoint.direction == EventConstants.USB_ENDPOINT_DIR_OUT) {
                        this.outEndpoint = endpoint;
                        this.maxOutSize = endpoint.maxPacketSize;
                    } else if (endpoint.direction == EventConstants.USB_ENDPOINT_DIR_IN) {
                        this.inEndpoint = endpoint
                        this.maxInSize = endpoint.maxPacketSize;
                    }
                }
            }

            if (!CheckEmptyUtils.isEmpty(this.outEndpoint) && !CheckEmptyUtils.isEmpty(this.inEndpoint)) {
                break;
            } else {
                this.outEndpoint = null;
                this.inEndpoint = null
            }
        }

        if (CheckEmptyUtils.isEmpty(this.outEndpoint) || CheckEmptyUtils.isEmpty(this.inEndpoint)) {
            console.info("usb init failed, outEndpoint or inEndpoint is null");
            return;
        }

        this.pip = usbManager.connectDevice(this.device);
        console.info("usb request connectDevice pipe: " + JSON.stringify(this.pip));
        if (CheckEmptyUtils.isEmpty(this.pip)) {
            this.result = "init error ： connectDevice failed";
            console.info("usb request connectDevice failed");
            return;
        }
    },
    initReadRequest() {
        if (this.isInitInRequest) {
            console.info("usb isInitInRequest, already init");
            prompt.showToast({
                message: "已经执行初始化",
                duration: 5000
            });
            return;
        }
        this.isInitInRequest = true;
        this.usbInRequest = usbManager.initializeRequest(this.pip, this.inEndpoint);
        if (CheckEmptyUtils.isEmpty(this.usbInRequest)) {
            this.isInitInRequest = false;
            this.result = "initReadRequest error ： 初始化request失败";
            console.info("usb in request init failed");
            return;
        }
        prompt.showToast({
            message: "读request初始化成功",
            duration: 5000
        });
        console.info("usb initReadRequest ----------end---------");
    },
    readData() {
        if (!this.isInitInRequest) {
            prompt.showToast({
                message: "请先确保初始化读的request执行成功",
                duration: 5000
            })
            console.info("usb readData, isInitInRequest is false");
            return;
        }
        if (CheckEmptyUtils.isEmpty(this.usbInRequest)) {
            this.result = "read error ： usbrequest 未初始化成功";
            prompt.showToast({
                message: "read request 未初始化成功,重启应用后重试",
                duration: 5000
            })
            console.info("usb readData, usbInRequest is null");
            return;
        }
        var readBuffer = new Uint8Array(this.inEndpoint.maxPacketSize);
        usbManager.queueRequest(this.usbInRequest, readBuffer).then(data =>{
            console.info("usb readData result : " + this.ab2str(data));
            console.info("usb readData buffer : " + data.toLocaleString());
            this.result = "readData ab2str result ：" + this.ab2str(data);
        }).catch(error=>{
            this.result = "readData error ：" + JSON.stringify(error);
            console.info("usb readData error : " + JSON.stringify(error));
        });
    },
    initWriteRequest() {
        console.info("usb initWriteRequest ----------begin---------");
        if (this.isInitOutRequest) {
            console.info("usb isInitOutRequest, already init");
            prompt.showToast({
                message: "已经执行初始化",
                duration: 5000
            })
            return;
        }
        this.isInitOutRequest = true;
        this.usbOutRequest = usbManager.initializeRequest(this.pip, this.outEndpoint);
        if (CheckEmptyUtils.isEmpty(this.usbOutRequest)) {
            this.isInitOutRequest = false;
            this.result = "initWriteRequest error ： 初始化request失败";
            console.info("usb out request initialize failed");
            return;
        }
        prompt.showToast({
            message: "写request初始化成功",
            duration: 5000
        })

        console.info("usb initWriteRequest ----------end---------");
    },
    writeData() {
        console.info("usb writeData ----------begin---------");
        if (!this.isInitOutRequest) {
            prompt.showToast({
                message: "请先确保初始化写的request执行成功",
                duration: 5000
            })
            console.info("usb writeData, isInitOutRequest is false");
            return;
        }
        if (CheckEmptyUtils.isEmpty(this.usbOutRequest)) {
            this.result = "write error ： usbrequest 未初始化成功";
            prompt.showToast({
                message: "write request 未初始化成功,重启应用后重试",
                duration: 5000
            })
            console.info("usb writeData, usbOutRequest is null");
            return;
        }

        console.info("usb writeData init data");
        var currentDate = "usb request test send current date " + (new DateUtils().nowWithSeconds());
        var buffData = this.str2ab(currentDate);

        console.info("usb request,begin queue data: " + currentDate);
        var isSend = usbManager.queueRequest(this.usbOutRequest, buffData).then(data =>{
            console.info("usb sendData result : " + this.ab2str(data));
            console.info("usb sendData buffer : " + data.toLocaleString());
            this.result = "sendData ab2str result ：" + this.ab2str(data);
        }).catch(error=>{
            this.result = "sendData error ：" + JSON.stringify(error);
            console.info("usb sendData error : " + JSON.stringify(error));
        });
        console.info("usb request,end queue result:" + isSend);
    },
    onBackPress() {
        router.back();
        this.onDestroy();
    },
    onDestroy() {
        if (!CheckEmptyUtils.isEmpty(this.usbInRequest) && this.isInitInRequest) {
            var freeResult = usbManager.finalizeRequest(this.usbInRequest);
            console.info("usb inrequest free " + freeResult);
        }
        if (!CheckEmptyUtils.isEmpty(this.usbOutRequest) && this.isInitOutRequest) {
            var outFreeResult = usbManager.finalizeRequest(this.usbOutRequest);
            console.info("usb outrequest free " + outFreeResult);
        }
        if (!CheckEmptyUtils.isEmpty(this.pip)) {
            console.info("usb pipe close result : "+ usbManager.close(this.pip));
        }

    },

// ArrayBuffer转为字符串，参数为ArrayBuffer对象
    ab2str(buf) {
        if (CheckEmptyUtils.isEmpty(buf)) {
            console.info("usb ab2str, buffer is null")
            return null;
        }
        return String.fromCharCode.apply(null, new Uint8Array(buf));
    },

// 字符串转为ArrayBuffer对象，参数为字符串
    str2ab(str) {
        var arr = [];
        for (var i = 0, j = str.length; i < j; ++i) {
            arr.push(str.charCodeAt(i));
        }
        var tmpUint8Array = new Uint8Array(arr);
        return tmpUint8Array;
    }
}
